﻿using BaseAuthRole.AspNetCore;
using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.DTO.Auth;
using BaseAuthRole.DTO.Knowledge;
using BaseAuthRole.DTO.Org;
using BaseAuthRole.IService;
using BaseAuthRole.Service;
using BaseAuthRole.Web.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RS.BaseModel.Common;
using RS.Tool.Base;
using System.Data;
using System.Drawing.Printing;
using System.Xml.Linq;

namespace BaseAuthRole.Web.Api.Client
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class KnowledgeAuthForClientController : ControllerBase
    {

        private IUserService _userService;
        public KnowledgeAuthForClientController(IUserService userService)
        {
            this._userService = userService;
        }
        /// <summary>
        /// 添加/编辑知识类别权限
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult AddKnowledgeAuth([FromBody] AddKnowledgeAuthInput input)
        {
            var result = new CommonResult();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { Uid = input.Uid, Id = "", AppId = "", AppAccessToken = "" }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("KnowledgeAuthManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            result.IsError = true;
            var relationActions = string.IsNullOrEmpty(input.Data) ? new List<string>() : input.Data.Split(',').ToList();

            if (string.IsNullOrEmpty(input.DocumentCategory) || string.IsNullOrEmpty(input.DocumentChildCategory))
            {
                result.Message = "类别,子类别不允许为空";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }

            if (!string.IsNullOrEmpty(input.KnowledgeAuthId))
            {

                var knowledgeAuth = this._userService.GetKnowledgeAuth(input.KnowledgeAuthId);

                if (knowledgeAuth == null)
                {
                    result.Message = "知识类别权限不存在";
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                    return Ok(result);
                }

                var check = this._userService.CheckKnowledgeAuth(knowledgeAuth, knowledgeAuth.Id);
                if (check == 1)
                {
                    result.Message = "类别,子类别已存在";
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                    return Ok(result);
                }

                knowledgeAuth.DocumentCategory = input.DocumentCategory;
                knowledgeAuth.DocumentChildCategory = input.DocumentChildCategory;
                knowledgeAuth.Description = input.Description;
                knowledgeAuth.UpdateUserId = input.Uid;

                var r = this._userService.UpdateKnowledgeAuth(knowledgeAuth, relationActions);

                if (r > 0)
                {
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                    result.Message = "修改成功";
                    result.IsError = false;
                }

            }
            else
            {
                var check = this._userService.CheckKnowledgeAuth(new KnowledgeAuth
                {
                    DocumentCategory = input.DocumentCategory,
                    DocumentChildCategory = input.DocumentChildCategory,
                });
                if (check == 1)
                {
                    result.Message = "类别,子类别已存在";
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                    return Ok(result);
                }

                var knowledgeAuth = new KnowledgeAuth
                {
                    DocumentCategory = input.DocumentCategory,
                    DocumentChildCategory = input.DocumentChildCategory,
                    Description = input.Description,
                    CreateUserId = input.Uid
                };
                var r = this._userService.CreateKnowledgeAuth(knowledgeAuth, relationActions);

                if (r > 0)
                {
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                    result.IsError = false;
                    result.Message = "添加成功";
                }
            }
            return Ok(result);
        }

        /// <summary>
        /// 获取知识类别权限列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetKnowledgeAuthList([FromQuery] GetAppInput input)
        {

            var result = new CommonResult<PageModel<KnowledgeAuth>>();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { Uid = input.Uid, Id = "", AppId = "", AppAccessToken = "" }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("KnowledgeAuthManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            var condition = "";
            long count = 0;
            Dictionary<string, object> obj = new Dictionary<string, object>();
            var info = this._userService.GetKnowledgeAuths(input.Page, input.PageSize, condition, " \"CreateTime\" desc", out count, obj);
            result.IsError = false;
            result.Result = new PageModel<KnowledgeAuth>()
            {
                Data = info,
                DataCount = count,
                Page = input.Page,
                PageCount = Convert.ToInt32(Math.Ceiling(count / (decimal)input.PageSize)),
                PageSize = input.PageSize
            };

            return Ok(result);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult DelKnowledgeAuth([FromQuery] DelKnowledgeAuthInput input)
        {
            var result = new CommonResult();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { Uid = input.Uid, Id = "", AppId = "", AppAccessToken = "" }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("KnowledgeAuthManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            int r = this._userService.DeleteKnowledgeAuth(input.KnowledgeAuthId);
            if (r <= 0)
            {
                result.IsError = true;
                result.Message = "删除失败";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }
            result.IsError = false;
            result.Message = "删除成功";
            return Ok(result);
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetKnowledgeAuth([FromQuery] DelKnowledgeAuthInput input)
        {
            var result = new CommonResult<GetKnowledgeAuthOutPut>();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { Uid = input.Uid, Id = "", AppId = "", AppAccessToken = "" }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("KnowledgeAuthManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            var info = this._userService.GetKnowledgeAuth(input.KnowledgeAuthId);
            if (info == null)
            {
                result.IsError = true;
                result.Message = "获取失败";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }
            result.IsError = false;
            result.Result = new GetKnowledgeAuthOutPut()
            {
                DocumentCategory = info.DocumentCategory,
                DocumentChildCategory = info.DocumentChildCategory,
                Description = info.Description,
                ObjectIds = this._userService.GetKnowledgeAuthRelation(input.KnowledgeAuthId)
            };
            return Ok(result);
        }
        
        /// <summary>
        /// 添加知识中心组织架构权限
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult AddKnowledgeAuthOrganization([FromBody] AddKnowledgeAuthOrganizationInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { Uid = input.Uid, Id = "", AppId = "", AppAccessToken = "" }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("KnowledgeAuthOrganization")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }
            return Ok(_userService.AddKnowledgeAuthOrganization(input));
        }

        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult DeleteKnowledgeAuthOrganization([FromQuery] DeleteKnowledgeAuthOrganizationInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { Uid = input.Uid, Id = "", AppId = "", AppAccessToken = "" }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("KnowledgeAuthOrganization")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }
            return Ok(_userService.DeleteKnowledgeAuthOrganization(input));
        }

        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetKnowledgeAuthOrganizationList([FromQuery] GetKnowledgeAuthOrganizationListInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { Uid = input.Uid, Id = "", AppId = "", AppAccessToken = "" }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("KnowledgeAuthOrganization")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }
            return Ok(_userService.GetKnowledgeAuthOrganizationList(input));
        }
    }
}
